package com.atguigu.chapter07.D04_State;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Author: Pepsi
 * Date: 2023/8/9
 * Desc:
 */
public class Flink04_State_Key_Value {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        env
                .socketTextStream("hadoop101", 9999) // socket只能是1
                .map(line -> {
                    String[] data = line.split(",");
                    return new WaterSensor(
                            data[0],
                            Long.valueOf(data[1]),
                            Integer.valueOf(data[2])
                    );
                })
                .keyBy(WaterSensor::getId)
                // 键控状态必须在keyBy后使用
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    // 状态
                    private ValueState<Integer> lastVcState;

                    // 每个并行度执行一次   初始化的时候执行一次
                    @Override
                    public void open(Configuration parameters) throws Exception {
//                        System.out.println("Flink04_State_Key_Value.open");
                        // 因为他已经把状态封装在运行时上下文了，所以直接获取就行了
                        lastVcState = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("lastVcState", Integer.class));
                    }

                    @Override
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {
                        // 获取状态里面的值  通过 .value() 方法
                        Integer lastVc = lastVcState.value();

                        System.out.println(lastVc+ "" +
                                "  " + value.getVc());

                        if (lastVc != null) {
                            if (value.getVc() >10 && lastVc > 10) {
                                out.collect(ctx.getCurrentKey()+" 连续两次超过10，发出红色预警...");
                            }
                        }

                        // 更新状态的值   只能保存一个值，所以用update更新
                        lastVcState.update(value.getVc());
                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
